package pers.jl.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import pers.jl.common.R;
import pers.jl.common.SMSUtils;
import pers.jl.service.IUserService;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author luge
 * @since 2023-04-22
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * 验证用户账号和验证码是否正确
     * @param map
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "map",value = "用户名密码封装的map集合")
    })
    public R login(@RequestBody Map<String,Object> map,HttpSession session){
        // 用户登录或者注册
        boolean res = userService.login(session, map);
        return res ? R.success("登录成功！") : R.error("登录失败！");
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/code/{phone}")
    @ApiOperation("发送短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "用户手机号")
    })
    public R sendCode(@PathVariable String phone, HttpSession session){

        // 1. 自定义发送验证码
        String code = "1234";
        // 2. 发送短信之后将验证码存到session中
        SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
        // 将电话号码作为key,验证码作为value，存在redis缓存中，过期时间为秒
        log.info("将电话号码作为key,验证码作为value，存在redis缓存中，过期时间为60秒");
        redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
        return R.success("短信发送成功！");
    }

}
